<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>CZLJChat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f0f2f5;
        }
        #chat-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
        }
        #chat-messages {
            height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #e3f2fd;
            margin-left: 20%;
            margin-right: 5px;
        }
        .bot-message {
            background-color: #f5f5f5;
            margin-right: 20%;
            margin-left: 5px;
        }
        #input-container {
            display: flex;
            gap: 10px;
        }
        #user-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
        }
        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .loading {
            color: #666;
            font-style: italic;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/crypto-js.min.js"></script>
</head>
<body>
    <div id="chat-container">
        <div id="chat-messages"></div>
        <div id="input-container">
            <input type="text" id="user-input" placeholder="输入你的问题...">
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script>
        const APPID = "";
        const API_KEY = "";
        const API_SECRET = "";
        const HOST = "spark-api.xf-yun.com";
        const PATH = "/v4.0/chat";
        let ws = null;
        let answerContent = '';

        function getWebSocketUrl() {
            const date = new Date().toUTCString();
            const signature_origin = `host: ${HOST}\ndate: ${date}\nGET ${PATH} HTTP/1.1`;
            const signature_sha = CryptoJS.HmacSHA256(signature_origin, API_SECRET);
            const signature = CryptoJS.enc.Base64.stringify(signature_sha);
            const authorization_origin = `api_key="${API_KEY}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;
            const authorization = btoa(authorization_origin);
            return `wss://${HOST}${PATH}?authorization=${authorization}&date=${encodeURIComponent(date)}&host=${encodeURIComponent(HOST)}`;
        }

        function sendMessage() {
            const userInput = document.getElementById('user-input');
            const question = userInput.value.trim();
            if (!question) return;
            addMessage(question, 'user');
            userInput.value = '';
            ws = new WebSocket(getWebSocketUrl());
            answerContent = '';
            ws.onopen = () => {
                const requestData = {
                    header: {
                        app_id: APPID,
                        uid: "12345"
                    },
                    parameter: {
                        chat: {
                            domain: "4.0Ultra",
                            temperature: 0.5,
                            max_tokens: 100
                        }
                    },
                    payload: {
                        message: {
                            text: [
                                { role: "user", content: question }
                            ]
                        }
                    }
                };
                ws.send(JSON.stringify(requestData));
            };
            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                if (data.header.code !== 0) {
                    addMessage(`错误：${data.header.message}`, 'bot');
                    ws.close();
                    return;
                }
                answerContent += data.payload.choices.text[0].content;
                updateLastMessage(answerContent);
                if (data.header.status === 2) {
                    ws.close();
                }
            };
            ws.onerror = (error) => {
                addMessage('连接发生错误', 'bot');
                console.error('WebSocket Error:', error);
            };
        }

        function addMessage(content, role) {
            const messagesDiv = document.getElementById('chat-messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}-message`;
            messageDiv.textContent = content;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function updateLastMessage(content) {
            const messages = document.getElementById('chat-messages').children;
            const lastMessage = messages[messages.length - 1];
            if (lastMessage && lastMessage.classList.contains('bot-message')) {
                lastMessage.textContent = content;
            } else {
                addMessage(content, 'bot');
            }
        }

        document.getElementById('user-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>